package com.mo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mo.common.Result;
import com.mo.entity.UserRole;
import com.mo.entity.params.UserSearchParams;
import com.mo.entity.PageVo;
import com.mo.entity.User;
import com.mo.service.UserRoleService;
import com.mo.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Optional;

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserRoleService userRoleService;

    /**
     * 添加用户
     */
    @PostMapping
    @PreAuthorize("hasAuthority('sys:system:user:add')")
    public Result add(@RequestBody User user) {
        User one = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, user.getUsername()));
        if (ObjectUtils.isNotEmpty(one)) {
            return Result.error("用户名已存在了，换一个吧", HttpServletResponse.SC_NOT_ACCEPTABLE);
        }

        // 加密用户密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        boolean save = userService.save(user);
        if (save) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 删除用户
     */
    @DeleteMapping
    @PreAuthorize("hasAuthority('sys:system:user:delete')")
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@RequestBody User user) {
        LambdaQueryWrapper<UserRole> wrapper = Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, user.getUserId());
        boolean remove = userRoleService.remove(wrapper);
        boolean save = userService.removeById(user);
        if (save && remove) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 修改用户
     */
    @PutMapping
    @PreAuthorize("hasAuthority('sys:system:user:update')")
    public Result update(@RequestBody User user) {
        boolean save = userService.updateById(user);
        if (save) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 查询用户列表
     */
    @GetMapping("list")
    public Result list(@RequestParam Integer pageNum,
                       @RequestParam Integer pageSize,
                       @RequestParam String username,
                       @RequestParam String realName,
                       @RequestParam String phone
    ) {
        UserSearchParams params = new UserSearchParams(pageNum, pageSize, username, realName, phone);
        PageVo<User> list = userService.list(params);
        return Result.success(list);
    }
}
